/* eslint-disable */

// 库
import * as Excel from './_export2Excel';

const isJson = str => {
  if (Array.isArray(str)) {
    if (str[0] instanceof Object) {
      return true;
    } else {
      return false;
    }
  } else if (str instanceof Object) {
    return true;
  }
  return false;
}

function s2ab(s) {
  var buf = new ArrayBuffer(s.length);
  var view = new Uint8Array(buf);
  for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xff;
  return buf;
}

function testGenExcelByTemplate(workbook) {
  workbook.Sheets['sheet']['A1']['v'] = 'xuhao';
  workbook.Sheets['sheet']['A1']['r'] = '<t>xuhao</t>';
  workbook.Sheets['sheet']['A1']['h'] = 'xuhao';
  workbook.Sheets['sheet']['A1']['w'] = 'xuhao';


  var wbout = window.XLSX.write(workbook, {
    bookType: 'xlsx',
    bookSST: false,
    type: 'binary'
  });
  var title = '列表';
  window.saveAs(
    new Blob([s2ab(wbout)], {
      type: 'application/octet-stream'
    }),
    title + '.xlsx'
  );
}

function testReadFile(file) {
  const reader = new FileReader()

  reader.onload = (e) => {
    const data = e.target.result;
    const workbook = XLSX.read(data, {
      type: "binary"
    });
    console.log(workbook);
    testGenExcelByTemplate(workbook);
  }
  reader.readAsBinaryString(file)
}

export default {
  install(Vue, options) {
    Vue.prototype.$xlsx = {
      // 导出 excel
      export (params) {
        if (!window.saveAs || !window.XLSX) {
          console.log(window.saveAs, window.XLSX, "not exist.");
          return;
        }
        return new Promise((resolve, reject) => {
          // 默认值
          const paramsDefault = {
            columns: [],
            data: [],
            title: 'table',
            header: null,
            merges: []
          };
          // 合并参数
          const _params = Object.assign({}, paramsDefault, params);
          // 从参数中派生数据
          const header = _params.columns.map(e => e.label);
          const data = _params.data.map(row =>
            _params.columns.map(col => {
              let data = row[col.prop];
              if (isJson(data)) {
                data = JSON.stringify(data);
              }
              return data;
            })
          );
          // console.log(header);
          // console.log(data);
          // 导出
          Excel.export_json_to_excel(header, data, _params.title, {
            merges: _params.merges,
            header: _params.header
          });
          // 完成
          resolve();
        });
      }, // 导入 xlsx
      import(file) {
        if (!window.saveAs || !window.XLSX) {
          console.log("cdn 引入的fileSaver或者xlsx不存在。");
          return;
        }
        const xlsx = window.XLSX;
        return new Promise((resolve, reject) => {
          const reader = new FileReader()
          const fixdata = data => {
            let o = ''
            let l = 0
            const w = 10240
            for (; l < data.byteLength / w; ++l) o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w, l * w + w)))
            o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w)))
            return o
          }
          const getHeaderRow = sheet => {
            const headers = []
            const range = xlsx.utils.decode_range(sheet['!ref'])
            let C
            const R = range.s.r
            for (C = range.s.c; C <= range.e.c; ++C) {
              var cell = sheet[xlsx.utils.encode_cell({
                c: C,
                r: R
              })]
              var hdr = 'UNKNOWN ' + C
              if (cell && cell.t) hdr = xlsx.utils.format_cell(cell)
              headers.push(hdr)
            }
            return headers
          }
          reader.onload = e => {
            const data = e.target.result
            const fixedData = fixdata(data)
            const workbook = xlsx.read(btoa(fixedData), {
              type: 'base64'
            })

            const firstSheetName = workbook.SheetNames[0]
            const worksheet = workbook.Sheets[firstSheetName]
            const header = getHeaderRow(worksheet)
            const results = xlsx.utils.sheet_to_json(worksheet)
            resolve({
              header,
              results
            })
          }
          reader.readAsArrayBuffer(file)
          // 测试导出excel模板生产的文件
          // testReadFile(file)
        })
      }
    }
  }
};
